﻿ 
#include "stdafx.h" 
#include "Config.h"
#include <ksfilefunc/ksfilefunc.h>
#include "export_functions.h"


Config::Config(const std::wstring& fullPath) throw(Error) : m_path(fullPath)
{
	m_ini.reset( new ksini::IniFile() );
	std::string temp;

	if( ksfilefunc::fileExistsW(fullPath.c_str() ) )
	{
		LoadString(temp, m_path.c_str() );
		m_ini->read_from_string(temp);
		return;
	}

	// not found
	SaveString(temp, m_path.c_str() );
	LoadString(temp, m_path.c_str() );
	m_ini->read_from_string(temp);

}

Config::~Config()
{
	try 
	{
		Save();
	}
	catch(Error e)
	{
		CoreHandleError(0, 0, e.what());
	}
	
}

void Config::Save() throw(Error)
{
	std::string temp;
	m_ini->write_to_string(temp);
	SaveString(temp, m_path.c_str() );
}


void Config::SaveString( const std::string& src, const WCHAR* filename ) throw(Error)
{
	FILE* file = _wfopen(filename , L"w+b");

	if(!file) 
	{
		throw std::runtime_error("error save file");
	}

	size_t swrtd = fwrite( src.c_str(), src.length(), 1,  file );
	fflush(file);
	fclose(file);
}

void Config::LoadString( std::string& dest,		 const WCHAR* filename ) throw(Error)
{
	dest = "";
	FILE* file = _wfopen( filename , L"r+b");

	if( NULL == file ) 
	{
		throw Error("error open file");
	}

	fseek( file, 0, SEEK_END );
	size_t file_size = ftell( file );	  
	fseek( file, 0, SEEK_SET );

	char* temp = new char[file_size + 1024];
	memset( temp, 0, file_size + 1024 );

	size_t read_res = fread(temp, file_size, 1, file);
	//if(0)//read_res != file_size)
	//{
	//	delete [] temp;
	//	throw std::runtime_error("Error read file");
	//}

	dest = temp;
	delete [] temp;
	fclose(file);
}

std::string Config::get_value(const std::string& sSection, 
					  const std::string& sKey, 
					  const std::string& default_value ) throw  (Error)
{
	std::string result;

	try
	{
		result = m_ini->get_value(sSection, sKey, default_value);
	}
	catch(std::runtime_error e)
	{
		throw Error(e.what());
	}
	
	return result;
}


void Config::set_value(const std::string& sSection, 
			   const std::string& sKey, 
			   const std::string& value,
			   const char* comment) throw  (Error)
{

	try
	{
		m_ini->set_value(sSection, sKey, value, comment);
	}
	catch(std::runtime_error e)
	{
		throw Error(e.what());
	}

}

